# serializers.py
import json
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.authtoken.serializers import AuthTokenSerializer
from .models import (
    Student,
    StudentGroup,
    UserProfile,
    ReadingMaterial,
    SingleChoiceQuestion,
    MultipleChoiceQuestion,
    FillInBlankQuestion,
    Task,
    Experiment,
    StudentExperimentProgress,
    StudentAnswerRecord,
    TeacherEvaluation,
    ExperimentAnnouncement,
    CodeQuestion,
    CodeSubmission
)

class LoginSerializer(AuthTokenSerializer):
    role = serializers.SerializerMethodField()
    user_id = serializers.IntegerField(source='id', read_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'role', 'user_id']
        extra_kwargs = {'password': {'write_only': True}}

    def validate(self, attrs):
        user = super().validate(attrs)
        return user  # 返回的是 validated_data['user']

class LoginSerializer(AuthTokenSerializer):
    role = serializers.SerializerMethodField()
    user_id = serializers.IntegerField(source='user.id', read_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'role', 'user_id']
        extra_kwargs = {'password': {'write_only': True}}

    def validate(self, attrs):
        validated_data = super().validate(attrs) 
        return validated_data

    def get_role(self, obj):
        try:
            return obj.userprofile.role
        except UserProfile.DoesNotExist:
            return None
# 学生信息序列化器
class StudentSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True, allow_null=True)
    password = serializers.CharField(
        write_only=True,
        required=False,
        style={'input_type': 'password'}
    )
    user = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(), 
        allow_null=True,
        required=False
    )

    class Meta:
        model = Student
        fields = ['id', 'user', 'username', 'password', 'name', 'age', 'gender', 'email', 'group_id']
        extra_kwargs = {
            'user': {'write_only': True}
        }
        
    def create(self, validated_data):
        # 提取密码（如果提供）
        password = validated_data.pop('password', None)
        
        # 如果提供了密码，创建新用户
        if password:
            user = User.objects.create_user(
                username=validated_data['name'],  # 使用email作为用户名
                email=validated_data['email'],
                password=password
            )
            validated_data['user'] = user
        
        # 创建学生记录
        return super().create(validated_data)

    def update(self, instance, validated_data):
        # 处理密码更新
        password = validated_data.pop('password', None)
        if password and instance.user:
            instance.user.set_password(password)
            instance.user.save()
        
        # 更新其他字段
        return super().update(instance, validated_data)

class StudentGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = StudentGroup
        fields = '__all__'

# 阅读材料序列化器
class ReadingMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReadingMaterial
        fields = '__all__'

# 单选题序列化器
class SingleChoiceQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SingleChoiceQuestion
        fields = '__all__'

# 多选题序列化器
class MultipleChoiceQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = MultipleChoiceQuestion
        fields = '__all__'

# 填空题序列化器
class FillInBlankQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = FillInBlankQuestion
        fields = '__all__'

# 任务序列化器
class TaskSerializer(serializers.ModelSerializer):
    reading_materials = ReadingMaterialSerializer(many=True, read_only=True)
    single_choice_questions = SingleChoiceQuestionSerializer(many=True, read_only=True)
    multiple_choice_questions = MultipleChoiceQuestionSerializer(many=True, read_only=True)
    fill_in_blank_questions = FillInBlankQuestionSerializer(many=True, read_only=True)

    class Meta:
        model = Task
        fields = '__all__'

# 实验序列化器

# 学生实验进度序列化器
class StudentExperimentProgressSerializer(serializers.ModelSerializer): 
    student_name = serializers.CharField(source='student.username', read_only=True)
    experiment_name = serializers.CharField(source='experiment.name', read_only=True)
    status = serializers.SerializerMethodField()
    completed_at = serializers.DateTimeField(source='submitted_at', format='%Y-%m-%d %H:%M', allow_null=True)

    class Meta:
        model = StudentExperimentProgress
        fields = [
            'id', 'student_name', 'experiment_name', 'status', 'completed_at', 'score'
        ]

    def get_status(self, obj):
        return '已完成' if obj.is_completed else '进行中'

# 学生答题记录序列化器
class StudentAnswerRecordSerializer(serializers.ModelSerializer):
    experiment_name = serializers.CharField(source='experiment.name', read_only=True)
    student_name = serializers.CharField(source='student.username', read_only=True)
    status = serializers.SerializerMethodField()
    completed_at = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    score = serializers.SerializerMethodField()
    max_score = serializers.SerializerMethodField()
    class Meta:
        model = StudentAnswerRecord
        fields = '__all__'
    def get_score(self, obj):
        progress = StudentExperimentProgress.objects.filter(
            student=obj.student, experiment=obj.experiment
        ).first()
        return progress.score if progress else None

    def get_max_score(self, obj):
        progress = StudentExperimentProgress.objects.filter(
            student=obj.student, experiment=obj.experiment
        ).first()
        return progress.max_score if progress else None
    def get_status(self, obj):
        return "已完成" if obj.completed_at else "未完成"
# 公共阅读材料序列化器
class PublicReadingMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = ReadingMaterial
        fields = ['id', 'title', 'content', 'created_at']

# 公共单选题序列化器
class PublicSingleChoiceQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SingleChoiceQuestion
        fields = ['id', 'text', 'option_a', 'option_b', 'option_c', 'option_d', 'correct_answer']

# 公共多选题序列化器
class PublicMultipleChoiceQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = MultipleChoiceQuestion
        fields = ['id', 'text', 'option_a', 'option_b', 'option_c', 'option_d', 'correct_answers']

# 公共填空题序列化器
class PublicFillInBlankQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = FillInBlankQuestion
        fields = ['id', 'text', 'correct_answer', 'fuzzy_answers']

# 公共任务序列化器
class PublicTaskSerializer(serializers.ModelSerializer):
    reading_materials = PublicReadingMaterialSerializer(many=True, read_only=True)
    single_choice_questions = PublicSingleChoiceQuestionSerializer(many=True, read_only=True)
    multiple_choice_questions = PublicMultipleChoiceQuestionSerializer(many=True, read_only=True)
    fill_in_blank_questions = PublicFillInBlankQuestionSerializer(many=True, read_only=True)

    class Meta:
        model = Task
        fields = ['id', 'name', 'reading_materials', 'single_choice_questions', 'multiple_choice_questions', 'fill_in_blank_questions']

# 公共实验序列化器
class PublicExperimentSerializer(serializers.ModelSerializer):
    tasks = PublicTaskSerializer(many=True, read_only=True)

    class Meta:
        model = Experiment
        fields = ['id', 'name', 'created_at', 'tasks']
# 新增教师评分序列化器
class TeacherEvaluationSerializer(serializers.ModelSerializer):
    class Meta:
        model = TeacherEvaluation
        fields = '__all__'
        read_only_fields = ('teacher', 'evaluated_at')

# 新增实验公告序列化器
class ExperimentAnnouncementSerializer(serializers.ModelSerializer):
    created_by = serializers.StringRelatedField()
    
    class Meta:
        model = ExperimentAnnouncement
        fields = '__all__'
        read_only_fields = ('created_by', 'created_at')

# 修改 ExperimentSerializer 包含更多教师相关字段
import json

import json

class ExperimentSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField()
    tasks = TaskSerializer(many=True, read_only=True)
    task_ids = serializers.PrimaryKeyRelatedField(
        queryset=Task.objects.all(), many=True, write_only=True, source='tasks'
    )

    class Meta:
        model = Experiment
        fields = '__all__'
        read_only_fields = ('created_by', 'created_at')
    def get_status(self, obj):
        user = self.context['request'].user
        try:
            progress = StudentExperimentProgress.objects.get(student=user, experiment=obj)
            return '已完成' if progress.is_completed else '进行中'
        except StudentExperimentProgress.DoesNotExist:
            return '未开始'

    def to_internal_value(self, data):
        if 'task_ids' in data and isinstance(data['task_ids'], str):
            try:
                import json
                data['task_ids'] = json.loads(data['task_ids'])
            except Exception:
                pass
    # 关键：把字符串数字转成数字
        if 'task_ids' in data and isinstance(data['task_ids'], list):
            data['task_ids'] = [int(i) for i in data['task_ids']]
        return super().to_internal_value(data)
# 新增教师端实验统计序列化器
class ExperimentStatisticsSerializer(serializers.Serializer):
    experiment_id = serializers.IntegerField()
    experiment_name = serializers.CharField()
    total_students = serializers.IntegerField()
    submitted_students = serializers.IntegerField()
    average_score = serializers.FloatField()
    completion_rate = serializers.FloatField()

class CodeQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = CodeQuestion
        fields = '__all__'

class CodeSubmissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = CodeSubmission
        fields = '__all__'
        read_only_fields = ['student']